//
//  MyTableViewController.m
//  18-SQLiteHomeWork
//
//  Created by 曹曹 on 16/8/8.
//  Copyright © 2016年 曹曹. All rights reserved.
//

#import "MyTableViewController.h"
#import "AddViewController.h"
#import "SQLiteDataBaseManager.h"
#import "MyTableViewCell.h"
#import "Student.h"
#import "DetailViewController.h"

@interface MyTableViewController () <AddViewControllerDelegate>
@property (nonatomic, strong) NSMutableArray *studentArray;
@property (nonatomic, strong) SQLiteDataBaseManager *dataBaseManager;
@end

@implementation MyTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
    _dataBaseManager = [SQLiteDataBaseManager sharedManager];
    [_dataBaseManager openSQLite];
    [self getStudentData];
}

- (void)getStudentData {
    self.studentArray = [NSMutableArray array];
    _studentArray = [_dataBaseManager selectAll];
    if (_studentArray == nil) {
        [_dataBaseManager createTable];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_studentArray) {
        return _studentArray.count;
    }
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse" forIndexPath:indexPath];
    if (_studentArray) {
        Student *stu = [_studentArray objectAtIndex:indexPath.row];
        cell.nameLabel.text = stu.stu_name;
        NSString *avatarsDirectory = [self getAvatarDirectory];
        NSString *imagePath = [avatarsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", stu.stu_name]];
        NSData *data = [NSData dataWithContentsOfFile:imagePath];
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            cell.avatarView.image = image;
        } else {
            NSString *path = [avatarsDirectory stringByAppendingPathComponent:@"default.png"];
            NSData *data = [NSData dataWithContentsOfFile:path];
            UIImage *image = [UIImage imageWithData:data];
            cell.avatarView.image = image;
        }
    }
    cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:0.5];
    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([sender isKindOfClass:[MyTableViewCell class]]) {
        MyTableViewCell *cell = sender;
        DetailViewController *detailVC = segue.destinationViewController;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        detailVC.student = [_studentArray objectAtIndex:indexPath.row];
    } else {
        AddViewController *addVC = segue.destinationViewController;
        addVC.delegate = self;
    }
}
// 传值协议方法
- (void)addStudent:(Student *)stu {
    if (![stu.stu_name isEqualToString:@""]) {
        [_dataBaseManager insertStu:stu];
        [self getStudentData];
        [_dataBaseManager closeSQLite];
    }
    [self.tableView reloadData];
}
#pragma mark - 删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [_dataBaseManager openSQLite];
        Student *stu = [_studentArray objectAtIndex:indexPath.row];
        [_studentArray removeObjectAtIndex:indexPath.row];
        [_dataBaseManager deleteStu:stu];
        NSFileManager *manager = [NSFileManager defaultManager];
        NSString *avatarsDirectory = [self getAvatarDirectory];
        NSString *imagePath = [avatarsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", stu.stu_name]];
        [manager removeItemAtPath:imagePath error:nil];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [_dataBaseManager closeSQLite];
    }
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}

- (NSString *)getAvatarDirectory {
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *avatarsDirectory = [[pathArray firstObject] stringByAppendingPathComponent:@"avatarsDirectory"];
    return avatarsDirectory;
}

@end
